//
//  RequestManager.m
//  片刻
//
//  Created by lanou3g on 15/6/4.
//  Copyright (c) 2015年 韩亚伟. All rights reserved.
//

#import "RequestManager.h"

@implementation RequestManager

//释放对象及其属性
- (void)dealloc
{
    self.delegate = nil;
    self.data = nil;
    self.parameterDict = nil;
    [super dealloc];
}

//初始化方法
- (instancetype)initWithRequestURL:(NSString *)urlString requestModel:(RequestModel)requestModel parameter:(NSString *)parameter{
    self = [super init];
    if (self) {
        _requestParameter = parameter;
        _requestURL = urlString;
        _requestModel = requestModel;
        self.parameterDict = [NSMutableDictionary dictionaryWithCapacity:10];
    }
    
    return self;
}

//开始请求
- (void)startRequest{
    NSURL *url = [NSURL URLWithString:_requestURL];
    NSMutableURLRequest *request= [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
    if (_requestModel == POST) {
        if (_requestParameter == nil) {
            [self parameterDictToString];
        }
        [request setHTTPMethod:@"POST"];
        [request setHTTPBody:[_requestParameter dataUsingEncoding:NSUTF8StringEncoding]];
        
    }
    [NSURLConnection connectionWithRequest:request delegate:self];
   
}

//把以字典方式储存的请求参数拼接成字符串
- (void)parameterDictToString{
    if (_parameterDict.count != 0) {
        NSMutableArray *parameterArray = [NSMutableArray arrayWithCapacity:10];
        for (NSString *key in _parameterDict) {
            NSString *str = [NSString stringWithFormat:@"%@=%@",key,_parameterDict[key]];
            [parameterArray addObject:str];
        }

        //该方法把数组中的元素以后面的字符串拼接起来形成一个字符串，并返回
        self.requestParameter = [parameterArray componentsJoinedByString:@"&"];
    }
}


//拼接返回得Data，执行多次
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    self.data = [NSMutableData data];
}
//在这里对自己的data进行初始化
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [self.data appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
//    NSLog(@"delegate 1 :%@", _delegate ? @"YES" : @"NO");
    if (_delegate && [_delegate respondsToSelector:@selector(requestDidFinishWithData:)]) {
        [_delegate requestDidFinishWithData:self.data];
        
    }
    if (_delegate && [_delegate respondsToSelector:@selector(requestDidFinishWithData:requestManager:)]) {
        [_delegate requestDidFinishWithData:self.data requestManager:self];
    }
//    NSLog(@"delegate 2 :%@", _delegate ? @"YES" : @"NO");

}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    if (_delegate && [_delegate respondsToSelector:@selector(requestError:)]) {
        [_delegate requestError:error];
    }
    
}

@end








































